package com.csliubo.eclipse.plugin.sqlgenerator.core.writer;

import java.io.File;
import java.io.FileWriter;
import java.util.List;

import com.csliubo.eclipse.plugin.sqlgenerator.core.model.Row;
import com.csliubo.eclipse.plugin.sqlgenerator.core.model.Table;
import com.csliubo.eclipse.plugin.sqlgenerator.util.StringUtils;

/**
 * 用于创建wiki数据
 * 
 * @author liubo.cs@hotmail.com
 * @version 1.0
 * @date 2011-3-5
 */
public class WikiWriter implements DataWriter {

    private static final String EXTENSION = ".wiki";
    private static final String ENCLOSER  = "|";

    public void write(String fileName, List<Table> tables) throws Throwable {
        File file = new File(fileName + EXTENSION);
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter writer = new FileWriter(file);

        for (Table table : tables) {
            writer.write(formatTableStr(table));
        }
        writer.flush();
    }

    public String formatTableStr(Table table) {
        StringBuilder sb = new StringBuilder();
        sb.append(StringUtils.enclose(table.getName(), ENCLOSER)).append(NEW_LINE);
        // 遍历，计算每个column最大的长度
        List<Row> rows = table.getRows();
        if (null != rows) {
            int columnNum = rows.get(0).getColumnNum();
            int[] columnMaxLen = new int[columnNum];
            for (Row row : rows) {
                for (int i = 0; i < columnNum; i++) {
                    String str = row.getColumns().get(i);
                    if (StringUtils.isBlank(str)) {
                        continue;
                    }
                    if (str.length() > columnMaxLen[i]) {
                        columnMaxLen[i] = row.getColumns().get(i).length()+1;
                    }
                }
            }
            for (Row row : table.getRows()) {
                for (int i = 0; i < columnNum; i++) {
                    sb.append(StringUtils.fillStrWithTab(ENCLOSER + row.getColumns().get(i), columnMaxLen[i]));
                }
                sb.append(ENCLOSER).append(NEW_LINE);
            }
        }
        sb.append(NEW_LINE);
        return sb.toString();
    }
}
